package com.xiaoyu.lanling.feature.main.controller

import `in`.srain.cube.concurrent.SimpleTask
import `in`.srain.cube.util.UTUtil
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.viewpager.widget.ViewPager.SimpleOnPageChangeListener
import com.xiaoyu.base.app.App
import com.xiaoyu.base.content.IntentRequest
import com.xiaoyu.base.data.UserData
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.MMKVUtil
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.event.accost.QuickAccostRecommendEvent
import com.xiaoyu.lanling.event.checkin.CheckInDialogDismissEvent
import com.xiaoyu.lanling.event.newtip.MainChatTipEvent
import com.xiaoyu.lanling.event.newtip.MomentNoticeEvent
import com.xiaoyu.lanling.event.voicecall.ChatCallServiceForegroundEvent
import com.xiaoyu.lanling.feature.accost.QuickAccostDialogFragment
import com.xiaoyu.lanling.feature.accost.data.AccostData
import com.xiaoyu.lanling.feature.conversation.MainConversationFragment
import com.xiaoyu.lanling.feature.conversation.RewardTipDialog
import com.xiaoyu.lanling.feature.fate.MainFateWrapperFragment
import com.xiaoyu.lanling.feature.mine.MainMineFragment
import com.xiaoyu.lanling.feature.moment.fragment.MainMomentFragment
import com.xiaoyu.lanling.feature.view.MainBottomAnimButton
import com.xiaoyu.lanling.feature.voicecall.util.VoiceCallNotificationUtils
import com.xiaoyu.lanling.util.TextViewUtil
import com.xiaoyu.lanling.view.FragmentAdapter
import com.xiaoyu.lanling.view.OnShowFragment
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivityViewController(val activity: FragmentActivity) : MainBottomAnimButton.OnCheckedChangeListener {

    companion object {
        const val MAIN_VIEW_PAGER_FATE = 0
        const val MAIN_VIEW_PAGER_MOMENT = 1
        const val MAIN_VIEW_PAGER_MESSAGE = 2
        const val MAIN_VIEW_PAGER_MINE = 3
    }

    private val requestTag = Any()
    private val fragments: MutableList<OnShowFragment> = mutableListOf()
    private var firstLaunch = true

    init {
        val initIndex = 0
        initViewPager(initIndex)
        gotoTabByIndex(initIndex)
        initBind()
        initEvent()
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(activity, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
            fun onEvent(event: MainChatTipEvent) {
                if (event.num <= 0) {
                    activity.bottom_chat_new_message_count.visibility = View.GONE
                } else {
                    TextViewUtil.displayFor99PlusType(activity.bottom_chat_new_message_count, event.num)
                }
            }

            @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
            fun onEvent(event: MomentNoticeEvent) {
                TextViewUtil.displayFor99PlusType(activity.main_bottom_notice_count, event.num)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CheckInDialogDismissEvent) {
                AccostData.accostRecommend(requestTag)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: QuickAccostRecommendEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }

                showQuickAccostRecommendDialog(event)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: ChatCallServiceForegroundEvent) {
                VoiceCallNotificationUtils.instance.dismissable = true
            }
        })
    }

    private fun showQuickAccostRecommendDialog(event: QuickAccostRecommendEvent) {
        if (event.users.isEmpty()) {
            return
        }

        (App.getInstance().topActivity as? FragmentActivity)?.let {
            if (it.isDestroyed || it.isFinishing) {
                return
            }
            QuickAccostDialogFragment.show(it.supportFragmentManager, ArrayList(event.users))
        }
    }

    private fun initBind() {
        activity.bottom_button_fate.setOnCheckedChangeListener(this)
        activity.bottom_button_moment.setOnCheckedChangeListener(this)
        activity.bottom_button_message.setOnCheckedChangeListener(this)
        activity.bottom_button_mine.setOnCheckedChangeListener(this)
    }

    private fun initViewPager(initIndex: Int) {
        val titles: MutableList<CharSequence> = ArrayList()
        titles.add("fate")
        titles.add("message")
        titles.add("mine")

        val params = Bundle()
        params.putInt(Constant.PARAM_INDEX, initIndex)

        val meetFragment = MainFateWrapperFragment()
        val momentFragment = MainMomentFragment()
        val chatFragment = MainConversationFragment()
        val personalFragment = MainMineFragment()

        meetFragment.arguments = params
        momentFragment.arguments = params
        chatFragment.arguments = params
        personalFragment.arguments = params

        fragments.add(meetFragment)
        fragments.add(momentFragment)
        fragments.add(chatFragment)
        fragments.add(personalFragment)

        val fragmentManager: FragmentManager = activity.supportFragmentManager
        val fragmentAdapter = FragmentAdapter(fragmentManager, fragments, titles)
        activity.main_view_pager.setSmoothScroll(false)
        activity.main_view_pager.offscreenPageLimit = fragments.size
        activity.main_view_pager.adapter = fragmentAdapter
        activity.main_view_pager.addOnPageChangeListener(object : SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                fragmentAdapter.tryShowOnIndex(position)
            }
        })
    }

    override fun onCheckedChanged(buttonView: MainBottomAnimButton, isSelected: Boolean) {
        if (!isSelected) {
            return
        }

        when (buttonView.id) {
            R.id.bottom_button_fate -> {
                activity.main_view_pager.currentItem = MAIN_VIEW_PAGER_FATE
                logForHomePageEvent()
            }
            R.id.bottom_button_moment -> {
                activity.main_view_pager.currentItem = MAIN_VIEW_PAGER_MOMENT
            }
            R.id.bottom_button_message -> {
                activity.main_view_pager.currentItem = MAIN_VIEW_PAGER_MESSAGE
                showRewardTipDialogIfNeed()
            }
            R.id.bottom_button_mine -> {
                activity.main_view_pager.currentItem = MAIN_VIEW_PAGER_MINE
            }
        }
        activity.bottom_button_fate.isSelected = activity.bottom_button_fate.id == buttonView.id
        activity.bottom_button_moment.isSelected = activity.bottom_button_moment.id == buttonView.id
        activity.bottom_button_message.isSelected = activity.bottom_button_message.id == buttonView.id
        activity.bottom_button_mine.isSelected = activity.bottom_button_mine.id == buttonView.id
    }

    private fun logForHomePageEvent() {
        if (firstLaunch) {
            UTUtil.getInstance().flushEvent("home_page", Bundle().apply { putString("form", "launch") })
            firstLaunch = false
        } else {
            UTUtil.getInstance().flushEvent("home_page", Bundle().apply { putString("form", "switch_pages") })
        }
    }

    private fun showRewardTipDialogIfNeed() {
        val hasShowRewardTipDialog = MMKVUtil.get()?.getBoolean(Constant.MMKVKey.KEY_HAS_SHOW_REWARD_TIP_DIALOG, UserData.getInstance().user.isMale)
                ?: true
        if (hasShowRewardTipDialog) {
            return
        }
        RewardTipDialog.show(activity.supportFragmentManager)
    }

    private fun gotoTabByIndex(index: Int) {
        when (index) {
            MAIN_VIEW_PAGER_FATE -> SimpleTask.postDelay({ activity.bottom_button_fate.isSelected = true }, 10)
            MAIN_VIEW_PAGER_MOMENT -> SimpleTask.postDelay({ activity.bottom_button_moment.isSelected = true }, 10)
            MAIN_VIEW_PAGER_MESSAGE -> SimpleTask.postDelay({ activity.bottom_button_message.isSelected = true }, 10)
            MAIN_VIEW_PAGER_MINE -> SimpleTask.postDelay({ activity.bottom_button_mine.isSelected = true }, 10)
        }
    }

    fun onNewIntent(intent: Intent?) {
        intent ?: return

        val intentRequest = IntentRequest.fromIntent(intent)
        val index = intentRequest.optInt(Constant.PARAM_INDEX, 0)
        gotoTabByIndex(index)
    }
}